# -*- coding: utf-8 -*-

#    Copyright (C) 2014 by Promotux
#                       di Francesco Meloni snc - http://www.promotux.it/

#    Author: Francesco Meloni  <francesco@promotux.it>

#    This file is part of OdCollect.

#    OdCollect is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 2 of the License, or
#    (at your option) any later version.

#    OdCollect is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.

#    You should have received a copy of the GNU General Public License
#    along with OdCollect.  If not, see <http://www.gnu.org/licenses/>.

import datetime
from web_lib.page import Page
from web_lib.webutils import Response, expose, json, salvaInSessione, leggiInSessione, permalinkaTitle
import Environment
from web_lib.webutils import leggiInSessione
from lib.utils import prep2json
from webEnv import *


@expose('/pg/cu_CategoriaCampo/<action>')
@expose('/pg/cu_CategoriaCampo/')
def customCategoriaCampo(req, action=None):
    """

    """
    from dao.Categoria import Categoria
    from dao.Campo import Campo
    from dao.CategoriaCampo import CategoriaCampo

    def __show__(req, action=None):
        categorie = Categoria().select(batchSize=None)
        campi = Campo().select(batchSize=None)
        catcam = CategoriaCampo().select(
            batchSize=None,
        )

        pageData = {'file': "/pg/cu_CategoriaCampo",
                    "categorie": categorie,
                    "campi": campi,
                    "catcam": catcam,
        }
        return Page(req).render(pageData)

    def __create__update__(req, action=None):
        """ """
        print "VEDIAMO", req.form.to_dict()
        idCategoria = req.form.get("id_categoria")
        idCategoriaCampo = req.form.getlist("id_categoriacampo")
        try:
            ordine = eval(req.form.get("ordine"))
        except:
            ordine = []
        if idCategoria != "None":
            tai = CategoriaCampo().select(id_categoria=int(idCategoria),orderBy="ordine", batchSize=None)
        if tai:
            for t in tai:
                t.delete()
        if type(ordine) ==type(1):
            ordine = [ordine]
        for a in ordine:
            d = CategoriaCampo()
            d.id_categoria = int(idCategoria)
            d.id_campo = int(a)
            d.ordine = ordine.index(a)+1
            d.persist()

        url_red = "/pg/cu_CategoriaCampo/"
        return Page(req).redirect(url_red)

    def __get_categorie_campi__(req, action=None):
        """ restituisce i campi associati"""
        idCategoria = req.args.get("id_categoria")
        a = []
        try:
            tai = CategoriaCampo().select(id_categoria=int(idCategoria),orderBy="ordine", batchSize=None)
        except:
            tai = []
        item = [str(d.id_campo) for d in tai]
        for i in item:
            aa = Campo().getRecord(id=i)
            a.append(aa)
        jasoned = json.dumps(prep2json(a), ensure_ascii=False, encoding='utf8')
        print "JASONED CAMPI ASSOCIATI", jasoned
        return Response(jasoned)

    def __get_campi__(req, action=None, tipo=None):
        """ Data una categoria resituisce quali campi abbia abbinati
        e l'ordine giusto"""
        idCategoria = req.args.get("id_categoria")
        try:
            tai = CategoriaCampo().select(id_categoria=int(idCategoria),orderBy="ordine", batchSize=None)
        except:
            tai = []
        idcampisel = [d.id_campo for d in tai]
        cai = Campo().select(batchSize = None)
        idcampi = [d.id for d in cai]
        for x in idcampisel:
            idcampi.remove(x)
        aaaa = Campo().select(idCampo=idcampi, batchSize=None)
        jasoned = json.dumps(prep2json(aaaa), ensure_ascii=False, encoding='utf8')
        return Response(jasoned)

    if leggiInSessione(req, sezione="Main", chiave="schema") is None:
        url_red = "/pg/main"
    elif action == "List":
        return __list__(req, action=action)
    elif action == "show":
        return __show__(req, action=action)
    elif action == "Create" or action == "Update":
        return __create__update__(req, action=action)
    elif action == "Delete":
        return __delete__(req, action=action)
    elif action == "Edit":
        return __edit__(req, action=action)
    elif action == "GetCategoriaCampo":
        return __get_categorie_campi__(req, action=action)
    elif action == "GetCampi":
        return __get_campi__(req, action=action)
    else:
        return __show__(req, action=action)
